package o2o.config;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@Aspect
@Component
public class RequestHandleTimeAspect {

    @Autowired
    private HttpServletRequest request;

    @Pointcut("execution(* o2o.web.actions..*.*(..))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //开始时间
        long startTime = System.currentTimeMillis();

        //执行代理目标方法
        Object obj = joinPoint.proceed();
//        Thread.sleep(200);


        Object target = joinPoint.getTarget();
        //代理目标对象类名
        String className = target.getClass().getSimpleName();
        if ("ActiveMQConfig".equalsIgnoreCase(className)
                || "JMSProperties_Market_V2".equalsIgnoreCase(className)
                || "InformationReleaseController".equalsIgnoreCase(className)
                || "MarketingDataUploadService".equalsIgnoreCase(className)
                || "MarketingService".equalsIgnoreCase(className)) {
            return obj;
        }


        //结束时间
        long endTime = System.currentTimeMillis();

        //处理时间
        long costTime = endTime - startTime;
        if (costTime < 200) {
            return obj;
        }

        //代理目标对象全限定类名
        String fullClassName = target.getClass().getName();
        //切点的方法名
        String methodName = joinPoint.getSignature().getName();

        //获取HttpServletResponse来自定义响应数据
//        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

        String uri = methodName;
        if (null != request) {
            try {
                uri = request.getRequestURI();
            } catch (Exception e) {
                System.out.println("request.getRequestURI(),error:" + className);
                return obj;
            }
        }
        if (costTime > 200 && costTime < 500) {
            System.out.println("【WARN】处理方法:" + fullClassName + "   " + uri + ", 处理请求耗时:" + costTime);
        } else if (costTime >= 500) {
            System.out.println("【!!! WARN】处理方法:" + fullClassName + "   " + uri + ", 处理请求耗时:" + costTime);
        } else {
//            System.out.println("处理方法:" + fullClassName + "  " + uri + ", 处理请求耗时:" + costTime);
        }

        return obj;
    }
}
